package model

import (
	"context"
	"database/sql"
	"errors"
	"fmt"
	"github.com/zeromicro/go-zero/core/stores/cache"
	"github.com/zeromicro/go-zero/core/stores/sqlx"
	"ns/pkg/consts"
	"time"
)

var (
	_                     UserModel = (*customUserModel)(nil)
	cacheMobileCodePrefix           = "cache:mobile:code:"
)

type (
	// UserModel is an interface to be customized, add more methods here,
	// and implement the added methods in customUserModel.
	UserModel interface {
		userModel
		FindOneByMobile(ctx context.Context, mobile string) (*User, error)
		UpdateStatusById(ctx context.Context, id, status int64) error
		SetMessageVerifyCode(ctx context.Context, mobile, code string) error
		GetMessageVerifyCode(ctx context.Context, mobile string) (string, error)
	}

	customUserModel struct {
		*defaultUserModel
	}
)

// NewUserModel returns a model for the database table.
func NewUserModel(conn sqlx.SqlConn, c cache.CacheConf, opts ...cache.Option) UserModel {
	return &customUserModel{
		defaultUserModel: newUserModel(conn, c, opts...),
	}
}

func (c *customUserModel) FindOneByMobile(ctx context.Context, mobile string) (*User, error) {
	var resp User
	query := fmt.Sprintf("select %s from %s where `mobile` = ? limit 1", userRows, c.table)
	err := c.QueryRowNoCacheCtx(ctx, &resp, query, mobile)
	switch {
	case err == nil:
		return &resp, nil
	case errors.Is(err, sqlx.ErrNotFound):
		return nil, ErrNotFound
	default:
		return nil, err
	}
}

func (c *customUserModel) UpdateStatusById(ctx context.Context, id, status int64) error {
	userIdKey := fmt.Sprintf("%s%v", cacheUserIdPrefix, id)
	_, err := c.ExecCtx(ctx, func(ctx context.Context, conn sqlx.SqlConn) (result sql.Result, err error) {
		query := fmt.Sprintf("update %s set %s where `id` = ?", c.table, "status=?")
		return conn.ExecCtx(ctx, query, status, id)
	}, userIdKey)
	return err
}

func (c *customUserModel) SetMessageVerifyCode(ctx context.Context, mobile, code string) error {
	cacheMobileCodeKey := fmt.Sprintf("%s%s", cacheMobileCodePrefix, mobile)
	err := c.SetCacheWithExpireCtx(ctx, cacheMobileCodeKey, code, consts.CacheExpire*time.Minute)
	return err
}

func (c *customUserModel) GetMessageVerifyCode(ctx context.Context, mobile string) (string, error) {
	cacheMobileCodeKey := fmt.Sprintf("%s%s", cacheMobileCodePrefix, mobile)
	code := ""

	err := c.GetCacheCtx(ctx, cacheMobileCodeKey, &code)
	return code, err
}
